<template>
  <div class="ra-md-editor">
    <v-md-editor
      :id="'editor' + Date.now()"
      v-model="text"
      :disabled-menus="[]"
      @upload-image="handleUploadImage"
      :height="height + 'px'"
    ></v-md-editor>
  </div>
</template>

<script setup>
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';

import { useSettingsStore } from '@/store';
import { ThemeEnum } from '@/enums';

import UploadAPI from '@/api/admin/upload';

// 应用主题（根据文档需在组件初始化前配置）

VMdEditor.use(vuepressTheme);

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  height: {
    type: String,
    default: '400',
  },
});

const emit = defineEmits(['update:modelValue']);

// 初始化编辑器内容
const text = ref(props.modelValue || '');

// 配置项
const settingsStore = useSettingsStore();

// 切换暗色主题
function enableDarkMode() {
  document.querySelector('.v-md-editor-preview').style.backgroundColor =
    '#1a1a1a';
  document.querySelector('.v-md-editor-preview').style.color = '#e0e0e0';
  document.querySelector('.v-md-editor__toolbar').style.backgroundColor =
    '#1a1a1a';
  document.querySelector('.v-md-editor__toolbar').style.color = '#e0e0e0';
}

// 切换亮色主题
function enableLightMode() {
  document.querySelector('.v-md-editor-preview').style.backgroundColor = '';
  document.querySelector('.v-md-editor-preview').style.color = '';
  document.querySelector('.v-md-editor__toolbar').style.backgroundColor = '';
  document.querySelector('.v-md-editor__toolbar').style.color = '';
}

// 切换 亮色 暗色 主题
watch(
  () => settingsStore.theme,
  (val) => {
    val === ThemeEnum.LIGHT ? enableLightMode() : enableDarkMode();
  },
);

// 监听内容变化
watch(
  () => props.modelValue,
  (val) => {
    text.value = val;
  },
);

watch(text, (val) => {
  emit('update:modelValue', val);
});

// 图片上传处理
const handleUploadImage = (event, insertImage, files) => {
  const formdata = new FormData();
  formdata.append('file', files[0]);
  formdata.append('edit', 1);
  UploadAPI.upload(formdata).then(({ data }) => {
    insertImage({ url: data.url, desc: '' });
  });
};

onMounted(() => {
  settingsStore.theme === ThemeEnum.LIGHT
    ? enableLightMode()
    : enableDarkMode();
});
</script>
<style lang="scss" scoped>
.ra-md-editor {
  width: 100%;
  padding: 5px;
  margin: 5px;
}
</style>
